package com.ruoyi.project.mysql.datasource;

import com.ruoyi.project.mysql.connection.ConnectionProxy;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DataSourceProxy extends AbstractDataSourceProxy{

    private String jdbcUrl;


    public DataSourceProxy(DataSource targetDataSource){
        super(targetDataSource);
        init(targetDataSource);
    }

    private void init(DataSource targetDataSource) {
        try (Connection connection = targetDataSource.getConnection()) {
            jdbcUrl = connection.getMetaData().getURL();
        } catch (SQLException e) {
            throw new IllegalStateException("can not init dataSource", e);
        }
    }

    /**
     * 获取原生的数据库链接
     * @return
     * @throws SQLException
     */
    public Connection getPlainConnection() throws SQLException {
        return targetDataSource.getConnection();
    }

    public Connection getPlainConnection(String username, String password) throws SQLException {
        return targetDataSource.getConnection(username, password);
    }

    @Override
    public Connection getConnection() throws SQLException {
        Connection plainConnection = getPlainConnection();
        return new ConnectionProxy(this,plainConnection);
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        Connection plainConnection = getPlainConnection(username,password);
        return new ConnectionProxy(this,plainConnection);
    }
}
